import { SSE } from "sse.js";
import * as R from "ramda";

function createSSE(
  url,
  headers = {},
  method = "GET",
  onMessage = R.identity,
  onError = R.identity,
  onStatus = R.identity
) {
  return (message, _headers = {}) => {
    let sse;
    sse = new SSE(url, {
      headers: R.mergeLeft(_headers, headers),
      payload: message,
      method,
      start: false,
    });
    sse.addEventListener("message", onMessage);
    sse.addEventListener("error", onError);
    sse.addEventListener("status", onStatus);

    return sse;
  };
}
function sendSSE(sse) {
  sse.stream();
  return sse;
}
function closeSSE(sse) {
  sse.close();
}

export { createSSE, sendSSE, closeSSE };
